package com._21cn.framework.base.db.jdbc;

import com._21cn.framework.base.db.BaseDao;
import com._21cn.framework.utils.PropertyUtil;
import com._21cn.framework.utils.SqlBuilder;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.flip.PageTurn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by 司徒海富 on 2017/2/4.
 */
public class BaseDaoJdbc<T> extends NamedParameterJdbcDaoSupport implements BaseDao<T> {

    public static final int DEFAULT_PAGE_SIZE = 100;   //如果调用分页方法的pageSize等于或小于0时，系统采用默认的pageSize为100

    private String sqlFilePath = "";

    public String getSqlFilePath() {
        return sqlFilePath;
    }

    public void setSqlFilePath(String sqlFilePath) {
        this.sqlFilePath = sqlFilePath;
    }

    public T toObject(Map<String, Object> map) {
        throw new UnsupportedOperationException( "the sub-class must override this method." );
    }

    public PageList<T> selectByMap(Map<String, Object> params, int pageNo, int pageSize, boolean doCount) {
        return query4PageList( getSqlFilePath() ,"selectByMap", params, pageNo, pageSize, doCount );
    }

    public PageList<T> selectByMap(Map<String, Object> params, int pageNo, int pageSize) {
        return selectByMap(params, pageNo, pageSize, true);
    }

    public T selectById(Object id) {
        return null;
    }

    public int selectCountByMap(Map<String, Object> params) {
        return 0;
    }

    public void insert(T object) {

    }

    public int batchInsert(Collection<T> objects) {
        return 0;
    }

    public int batchInsert(T... objects) {
        return 0;
    }

    public int updateByMap(Map<String, Object> params) {
        return 0;
    }

    public int update(T object) {
        return 0;
    }

    public int batchUpdate(Collection<T> objects) {
        return 0;
    }

    public int batchUpdate(T... objects) {
        return 0;
    }

    public int deleteByMap(Map<String, Object> params) {
        return 0;
    }

    public int deleteById(Object id) {
        return 0;
    }

    public int batchDeleteById(Collection<?> objects) {
        return 0;
    }

    public int batchDeleteById(Object[] objects) {
        return 0;
    }


    //========================================其 它==========================================================
    /**
     * 根据参数获取分页数据，每查询一次都会统计符合条件的总条数
     */
    protected PageList<T> query4PageList( String filePath,  String sqlMapId, Map<String, Object> params, int page, int pageSize ) {
        return query4PageList( filePath, sqlMapId, params, new PageTurn( page, pageSize ), true );
    }

    protected PageList<T> query4PageList( String filePath, String sqlMapId, Map<String, Object> params, int page, int pageSize, boolean doCount ) {
        return query4PageList(filePath, sqlMapId, params, new PageTurn( page, pageSize ), doCount );
    }

    protected PageList<T> query4PageList( String filePath, String sqlMapId, Map<String, Object> params, PageTurn turn, boolean doCount ) {
        PageTurn retTurn = initParamAndPageTurn(filePath, sqlMapId + "_count", params, turn, doCount );
        PageList pagelist = new PageList();
        pagelist.setPageTurn( retTurn );
        if( retTurn.getRowCount().intValue() > 0 ) {
            try {
                String sql = PropertyUtil.getProperty(filePath, sqlMapId);
                JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
                SqlBuilder sb = new SqlBuilder(sql).combineWhere(params);
                sb.appendStatement(" limit " + retTurn.getStart() + ", " + retTurn.getPageSize());
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toStatement());
                List results = new ArrayList();
                for (Map<String, Object> map : list) {
                    T object =  toObject(map);
                    if (object != null) {
                        results.add(object);
                    }
                }
                pagelist.addAll( results );
            }catch( Exception e ) {
                e.printStackTrace();
            }
        }
        return pagelist;
    }

    private PageTurn initParamAndPageTurn(String filePath, String sqlMapId, Map<String, Object> params, PageTurn turn, boolean doCount ){
        PageTurn retTurn = new PageTurn();
        int total = -1;
        if( doCount || turn.getPageSize().intValue() == 0 )
            total = queryCount( filePath, sqlMapId, params );
        if( total < 0 )
            total = turn.getRowCount().intValue();
        if( total > 0 ) {
            int tempPageSize = turn.getPageSize().intValue();
            if( tempPageSize <= 0 )
                tempPageSize = total > DEFAULT_PAGE_SIZE ? DEFAULT_PAGE_SIZE : total;
            retTurn.initWithPage( turn.getPage().intValue(), tempPageSize, total );
            params.put( "pageTurn", retTurn );
            params.put( "pageTurnStartRow", retTurn.getStart() );
            params.put( "pageTurnEndRow", retTurn.getEnd() );
        }
        return retTurn;
    }

    /**
     * @param sqlMapId sql语句id
     * @param params 查询参数
     * @return count结果
     */
    protected int queryCount(String filePath, String sqlMapId, Map<String, Object> params ) {
        String sql = PropertyUtil.getProperty( filePath , sqlMapId );
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
        SqlBuilder sb = new SqlBuilder(sql).combineWhere(params);
        Number number = jdbcTemplate.queryForObject(sb.toStatement(), Integer.class);
        return (number != null ? number.intValue() : 0);
    }


}
